package com.liushuai.eas.controller;

import com.alibaba.fastjson.JSON;
import com.liushuai.eas.common.ConversionUtil;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.*;

import com.liushuai.eas.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/timetable")
public class LessonController {

    @Resource
    private LessonImp lessonImp;

    @Resource
    private ClassroomImp classroomImp;

    @Resource
    private TeacherImp teacherImp;

    @Resource
    private CourseImp courseImp;

    @Resource
    private ClassesImp classesImp;

    @Resource
    private BuildingImp buildingImp;

    private final String[] week = {"星期一","星期二","星期三","星期四","星期五"};
    private final String[] section = {"one","two","three","four","five","six","seven","eight"};
    private final String[] startTime = {"08:00","08:55","09:55","10:50","13:50","14:45","15:40","16:20"};

    @PostMapping
    public Result<?> add(@RequestBody Map<String,Object> map){

        System.out.println(map);

        int courseId = Integer.parseInt(map.get("courseId").toString());
        int teacherId = Integer.parseInt(map.get("teacherId").toString());
        int classId = Integer.parseInt(map.get("classId").toString());
        int classroomId = Integer.parseInt(map.get("classroomId").toString());
        String year = map.get("year").toString();
        List<String> week = ConversionUtil.objToList(map.get("week"), String.class);
        List<Integer> weeks = ConversionUtil.objToList(map.get("weeks"), Integer.class);
        List<String> time = ConversionUtil.objToList(map.get("time"), String.class);

        List<Lesson> lessonList = new ArrayList<>();

        for(Integer i : weeks){
            for(String j : week){
                for(String k : time){
                    String[] split = k.split("-");
                    if (lessonImp.queryConflict(year,i,j,split[0],split[1],classroomId)!=null){
                        continue;
                    }
                    int sort = 0;
                    Lesson lesson = new Lesson();
                    lesson.setCourseId(courseId);
                    lesson.setTeacherId(teacherId);
                    lesson.setClassId(classId);
                    lesson.setClassroomId(classroomId);
                    lesson.setYear(year);
                    lesson.setWeeks(i);
                    lesson.setWeek(j);
                    if ("星期一".equals(j)){
                        sort = 1;
                    }else if ("星期二".equals(j)){
                        sort = 2;
                    }else if ("星期三".equals(j)){
                        sort = 3;
                    }else if ("星期四".equals(j)){
                        sort = 4;
                    }else if ("星期五".equals(j)){
                        sort = 5;
                    }
                    lesson.setSort(sort);
                    lesson.setStartTime(split[0]);
                    lesson.setEndTime(split[1]);
                    lessonList.add(lesson);
                }
            }
        }
        System.out.println(lessonList);
        for (Lesson lesson : lessonList){
            //插入lesson数据库
            if (lessonImp.insert(lesson)!=1)
                return Result.fail(lesson);
        }

        return Result.success();
    }

    @PutMapping
    public Result<Lesson> update(@RequestBody Map<String,Object> map){

        int courseId = Integer.parseInt(map.get("courseId").toString());
        int teacherId = Integer.parseInt(map.get("teacherId").toString());
        int classId = Integer.parseInt(map.get("classId").toString());
        int classroomId = Integer.parseInt(map.get("classroomId").toString());

        if (lessonImp.deleteTimetable(courseId, teacherId, classId, classroomId)==0)
            return Result.fail();

        add(map);

        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String year,
                              @RequestParam(defaultValue = "-1") Integer classroomId,
                              @RequestParam(defaultValue = "-1") Integer teacherId,
                              @RequestParam(defaultValue = "-1") Integer classId,
                              @RequestParam(defaultValue = "-1") Integer courseId){

        List<Timetable> lessonList = new ArrayList<>();
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();

        lessonList = lessonImp.queryLessonList((pageNum - 1) * pageSize, pageSize,classroomId,courseId,classId,teacherId,year);
        total = lessonList.size();

        List<Object> list = new ArrayList<>();

        for (Timetable timetable : lessonList){
            Map<String, Object> timetableMap = new HashMap<>();
            List<Integer> weeksList = new ArrayList<>();
            List<String> timeList = new ArrayList<>();
            List<String> weekList = new ArrayList<>(Arrays.asList(timetable.getWeek().split(",")));
            List<String> startTimeList = new ArrayList<>(Arrays.asList(timetable.getStartTime().split(",")));
            List<String> endTimeList = new ArrayList<>(Arrays.asList(timetable.getEndTime().split(",")));
            timetableMap.put("course",courseImp.selectOne(timetable.getCourseId()));
            timetableMap.put("teacher",teacherImp.selectOne(timetable.getTeacherId()));
            timetableMap.put("class",classesImp.selectOne(timetable.getClassId()));
            timetableMap.put("classroom",classroomImp.selectOne(timetable.getClassroomId()));

            for (String weeks : timetable.getWeeks().split(",")){
                weeksList.add(Integer.parseInt(weeks));
            }

            for (int i = 0; i < startTimeList.size(); i++) {
                timeList.add(startTimeList.get(i) + "-" + endTimeList.get(i));
            }

            timetableMap.put("weeks",weeksList);
            timetableMap.put("week",weekList);
            timetableMap.put("time",timeList);
            timetableMap.put("year",timetable.getYear());

            list.add(timetableMap);
        }

        map.put("records", list);
        map.put("total",total);
        map.put("pageSize",pageSize);
        return Result.success("数据加载成功",map);
    }

    @DeleteMapping
    public Result<Lesson> delete(@RequestBody Map<String,Object> map){

        Teacher teacher = JSON.parseObject(JSON.toJSONString(map.get("teacher")),Teacher.class);
        Classroom classroom = JSON.parseObject(JSON.toJSONString(map.get("classroom")),Classroom.class);
        Classes classes = JSON.parseObject(JSON.toJSONString(map.get("class")),Classes.class);
        Course course = JSON.parseObject(JSON.toJSONString(map.get("course")),Course.class);

        if (lessonImp.deleteTimetable(course.getId(), teacher.getId(), classes.getId(), classroom.getId())==0)
            return Result.fail();

        return Result.success();
    }

    @PostMapping("/queryClassTimetable")
    public Result<List<Map<String,Object>>> queryClassLesson(@RequestBody Map<String,String> map){
        int classId = Integer.parseInt(map.get("classId"));
        int weeks = Integer.parseInt(map.get("weeks"));
        String year = map.get("year");

        List<Lesson> lessonList = addData(lessonImp.queryClassLesson(classId, weeks, year));

        List<Map<String,Object>> resultList = new ArrayList<>();
        for (String s : week) {//按周循环
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("week", s);//周
            for (int j = 0; j < section.length; j++) {//按节次循环
                resultMap.put(section[j], "");
                for (Lesson lesson : lessonList) {//循环按条件查询出来的课程 目的:将查询出来的课程放置对应课表位置
                    HashMap<String, Object> sectionDataMap = new HashMap<>();
                    if (lesson.getWeek().equals(s) && lesson.getStartTime().equals(startTime[j])) {
                        sectionDataMap.put("course",lesson.getCourse().getName());
                        sectionDataMap.put("teacher",lesson.getTeacher().getName());
                        sectionDataMap.put("classroom",lesson.getClassroom().getName());
                        sectionDataMap.put("building",lesson.getClassroom().getBuilding().getName());
                        resultMap.put(section[j], sectionDataMap);
                    }
                }
            }
            resultList.add(resultMap);
        }

        return Result.success(resultList);
    }

    @PostMapping("/queryTeacherTimetable")
    public Result<List<Map<String,Object>>> queryTeacherLesson(@RequestBody Map<String,String> map){

        int teacherId = Integer.parseInt(map.get("teacherId"));
        int weeks = Integer.parseInt(map.get("weeks"));
        String year = map.get("year");

        List<Lesson> lessonList = addData(lessonImp.queryTeacherLesson(teacherId, weeks, year));

        List<Map<String,Object>> resultList = new ArrayList<>();
        for (String s : week) {//按周循环
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("week", s);//周
            for (int j = 0; j < section.length; j++) {//按节次循环
                resultMap.put(section[j], "");
                for (Lesson lesson : lessonList) {//循环按条件查询出来的课程 目的:将查询出来的课程放置对应课表位置
                    HashMap<String, Object> sectionDataMap = new HashMap<>();
                    if (lesson.getWeek().equals(s) && lesson.getStartTime().equals(startTime[j])) {
                        sectionDataMap.put("course",lesson.getCourse().getName());
                        sectionDataMap.put("class",lesson.getClasses().getName());
                        sectionDataMap.put("classroom",lesson.getClassroom().getName());
                        sectionDataMap.put("building",lesson.getClassroom().getBuilding().getName());
                        resultMap.put(section[j], sectionDataMap);
                    }
                }
            }
            resultList.add(resultMap);
        }

        return Result.success(resultList);
    }

    //对课表进行初始化
    private List<Lesson> addData(List<Lesson> lessonList){
        for (Lesson lesson : lessonList){
            lesson.setClassroom(classroomImp.selectOne(lesson.getClassroomId()));
            lesson.setCourse(courseImp.selectOne(lesson.getCourseId()));
            lesson.setTeacher(teacherImp.selectOne(lesson.getTeacherId()));
            lesson.setClasses(classesImp.selectOne(lesson.getClassId()));
            lesson.getClassroom().setBuilding(buildingImp.selectOne(lesson.getClassroom().getBuildingId()));
        }
        return lessonList;
    }

    @PostMapping("/queryClassCourse")
    public Result<List<Map<String,Object>>> queryClassCourse(@RequestBody Map<String,Integer> paramMap){

        Integer classId = paramMap.get("classId");

        List<Map<String, Object>> maps = lessonImp.queryClassCourse(classId);
        for (Map<String, Object> map : maps){
            ArrayList<Course> courseList = new ArrayList<>();
            String[] coursesId = String.valueOf(map.get("coursesId")).split(",");
            for (String courseId : coursesId){
                courseList.add(courseImp.selectOne(Integer.parseInt(courseId)));
            }
            map.put("courses",courseList);
        }

        return Result.success(maps);
    }

}
